import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Spin,
  Row,
  Empty,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Table,
} from 'antd';
import moment from 'moment';
import router from 'umi/router';

import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './Test.less';
import XLSX from '../../../assets/xlsx.min';
import { getDateList } from '../../../services/mail_service';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

/* eslint react/no-multi-comp:0 */
@connect(({ fund, loading }) => ({
  fund,
  loading: loading.models.ruleTest,
}))
@Form.create()
class BillGradeRiskControl extends PureComponent {
  state = {
    filterData: [],
    expandForm: false, // 查询菜单栏 是否显示
    listLoading: false,
    formValues: {
      billType: 1,
      stock: '',
    }, // 查询菜单栏   查询参数
    modalVisible: false,
    updateModalVisible: false,

    selectedRows: [],

    stepFormValues: {},

    dataTradeList: {},
    updateParam: true,

    HistogramModalVisible: false,

    suggestions: [],
    textboxValues: {
      key: '',
      type: 1,
    },
  };

  indexCountColumns = [];

  groupRender = (value, row, index) => {
    const obj = {
      children: value,
      props: {},
    };

    if (this.indexCountColumns.length > 0) {
      let isHave = false;
      for (let i = 0; i < this.indexCountColumns.length; i++) {
        if (index === this.indexCountColumns[i].index) {
          isHave = true;
          obj.props.rowSpan = this.indexCountColumns[i].count;
        }
      }
      if (!isHave) {
        if (value) {
          obj.props.rowSpan = 0;
          obj.props.colSpan = 0;
        }
      }
    }
    return obj;
  };

  /*  groupRenderBillId = (value,row, index) => {
    const obj = {
      children: value,
      props: {},
    };
    if (this.indexCountColumns.length>0){
      let isHave = false;
      for (let i = 0; i < this.indexCountColumns.length; i++) {
        if (index ===this.indexCountColumns[i].index){
          isHave = true;
          obj.props.rowSpan = this.indexCountColumns[i].count;
        }
      }
      if (!isHave){
        if (value) {
          obj.props.rowSpan = 0;
          obj.props.colSpan = 0;
        }
      }
    }
    obj.children= <span style={{ color: 'red' }}>{value}</span>;
    return obj;
  } */

  renderContentBase = (value, row, index) => {
    const obj = {
      children: value,
      props: {},
    };
    return obj;
  };

  columns = [
    {
      title: '序号',
      dataIndex: 'billId',
      render: this.groupRender,
      // render:this.groupRenderBillId,
      key: 'billId',
      sorter: (a, b) => a.billId - b.billId,
    },
    {
      title: '编号',
      dataIndex: 'billNumber',
      render: this.groupRender,
      key: 'billNumber',
    },
    {
      title: '类型',
      dataIndex: 'name',
      render: this.groupRender,
      key: 'name',
      width: 100,
    },
    {
      title: '股票名称',
      dataIndex: 'stock',
      render: this.renderContentBase,
      key: 'stock',
    },
    {
      title: '成本价',
      dataIndex: 'costPrice',
      render: this.renderContentBase,
      key: 'costPrice',
      sorter: (a, b) => a.costPrice - b.costPrice,
    },
    {
      title: '最新价',
      dataIndex: 'nowPrice',
      render: this.renderContentBase,
      key: 'nowPrice',
      sorter: (a, b) => a.nowPrice - b.nowPrice,
    },

    /*    {
      title: '数量（股）',
      dataIndex: 'amount',
      render:this.renderContentBase,
      key: 'amount',
      sorter: (a, b) => a.amount - b.amount,
    }, */
    {
      title: '市值',
      dataIndex: 'marketValue',
      render: this.renderContentBase,
      key: 'marketValue',
      sorter: (a, b) => a.marketValue - b.marketValue,
    },
    {
      title: '持仓比例',
      dataIndex: 'positionPer',
      render: this.renderContentBase,
      key: 'positionPer',
    },
    /*    {
      title: '盈亏',
      dataIndex: 'profit',
      render:this.renderContentBase,
      key: 'profit',
    },
    {
      title: '盈亏百分比',
      dataIndex: 'profitPer',
      render:this.renderContentBase,
      key: 'profitPer',
    }, */
    {
      title: '距离执行价',
      dataIndex: 'toStrikePriceRate',
      render: this.renderContentBase,
      key: 'toStrikePriceRate',
    },
    {
      title: '报警百分比',
      dataIndex: 'warningPer',
      render: this.renderContentBase,
      key: 'warningPer',
    },
    {
      title: '财报日期',
      dataIndex: 'earningsDate',
      render: this.renderContentBase,
      key: 'earningsDate',
    },
    {
      title: '票据到期日',
      dataIndex: 'billDueDate',
      render: this.renderContentBase,
      key: 'billDueDate',
    },

    /*    {
      title: '对方赎回值',
      dataIndex: 'redemptionValue',
      render:this.renderContentBase,
      key: 'redemptionValue',
    }, */
    {
      title: '所属行业',
      dataIndex: 'industry',
      render: this.renderContentBase,
      key: 'industry',
    },
    {
      title: '已完成的票据',
      dataIndex: 'stockInBillCount',
      render: this.renderContentBase,
      key: 'stockInBillCount',
    },
  ];

  // 默认加载数据-起始方法
  render() {
    const {
      fund: { billriskdata },
      loading,
      total,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      listLoading,
    } = this.state;
    const newdata = {
      list: [],
      pagination: '',
    };
    if (billriskdata.code == 1) {
      newdata.list = billriskdata.list;
      newdata.pagination = billriskdata.pagination;
    }

    this.indexCountColumns = [];
    let indexTemp = 0;
    let countTemp = 1;
    for (let i = 0; i < newdata.list.length; i++) {
      newdata.list[i].key = `00${i}`;
      newdata.list[i].costPrice = parseFloat(newdata.list[i].costPrice).toFixed(4);
      newdata.list[i].nowPrice = parseFloat(newdata.list[i].nowPrice).toFixed(4);
      if (newdata.list[i].billDueDate.length > 10) {
        newdata.list[i].billDueDate = newdata.list[i].billDueDate.substring(0, 10);
      }
      if (newdata.list[i].earningsDate && newdata.list[i].earningsDate.length > 10) {
        newdata.list[i].earningsDate = newdata.list[i].earningsDate.substring(0, 10);
      }

      if (i > 0) {
        if (newdata.list[i].billId === newdata.list[i - 1].billId) {
          countTemp++;
          if (i === newdata.list.length - 1) {
            this.indexCountColumns.push({
              index: indexTemp,
              count: countTemp,
            });
          }
        } else {
          this.indexCountColumns.push({
            index: indexTemp,
            count: countTemp,
          });
          indexTemp = i;
          countTemp = 1;
          if (i === newdata.list.length - 1) {
            this.indexCountColumns.push({
              index: indexTemp,
              count: countTemp,
            });
          }
        }
      }
    }
    const { HistogramModalVisible } = this.state;
    const HistogramMethods = {
      handleHistogramVisible: this.handleHistogramVisible,
    };
    return (
      <PageHeaderWrapper title="票据列表">
        {/*        <div className={styles.controlBar}>
          <div
            style={{
              display: 'flex',
              flexFlow: 'row wrap',
              alignContent: 'space-between',
              alignItems: 'center',
            }}
          >
            <Button type="primary" className={styles.optionsbutton} onClick={() => this.upload(true)}>
              上传
            </Button>
            <input className="fileipt" type="file"/>
            <Button type="primary" className={styles.optionsbutton} onClick={() => this.search()}>
              查询
            </Button>
          </div>
        </div> */}
        <Card bordered={false}>
          <div className={styles.tableList}>
            {/* <div className={styles.tableListForm}>{this.renderForm()}</div> */}
            <div className={styles.paginationMsg}>
              {'共'} {newdata.pagination.total} {'条数据'}
            </div>
            <br />
            {newdata.list.length == 0 ? (
              <div
                style={{
                  textAlign: 'center',
                  borderRadius: 4,
                  marginBottom: 20,
                  marginTop: 20,
                  padding: '30 50',
                  margin: '20 20',
                }}
              >
                {' '}
                <Spin size="large" />{' '}
              </div>
            ) : (
              <Table pagination={false} columns={this.columns} dataSource={newdata.list} bordered />
            )}
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }

  // 加载完 之后 再加载 此 方法
  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'fund/GetBillRiskManage',
      payload: formValues,
      callback: response => {},
    });
  }

  // 改变每页条数和当前页
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    formValues.page = pagination.current;
    formValues.pagesize = pagination.pageSize;
    const params = {
      ...formValues,
    };
    dispatch({
      type: 'fund/GetFundTwoTradeList',
      payload: params,
    });
  };

  // 判断 菜单栏 是 缩放显示 还是 全部展示
  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  // 菜单栏- 点击展开显示 事件
  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最大财报日">
              {getFieldDecorator('maxEarningsDate ')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最大财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小财报日">
              {getFieldDecorator('minEarningsDate')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最小财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小保本幅度">
              {getFieldDecorator('minBreakEvenMargin')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最小权利金">
              {getFieldDecorator('minRoyalty')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小收益率">
              {getFieldDecorator('minYieldRate')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div>
      </Form>
    );
  }

  // 菜单栏 默认收缩显示 事件
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.search} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={14} sm={24}>
            <FormItem label="股票代码">
              {getFieldDecorator('stockId')(
                <Select
                  showSearch
                  style={{ width: '100%' }}
                  placeholder="请输入股票代码"
                  onSearch={this.onSearch.bind(this)}
                  onSelect={this.onSelect.bind(this)}
                >
                  {this.state.suggestions}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={10} sm={24}>
            <span className={styles.submitButtons}>
              {/*              <Button type="primary" htmlType="submit" >
                查询
              </Button> */}
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              {/*            <Button style={{marginLeft: 8}} className={styles.optionsbutton} type="primary" onClick={() => this.upload(true)}>
              上传
            </Button> */}
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  // 菜单栏-查询按钮 事件
  handleSearch = e => {
    e.preventDefault();
    const {
      dispatch,
      form,
      fund: { data },
    } = this.props;
    const { formValues, dataTradeList } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      data.rows = dataTradeList.filter(
        (item, index, arr) => item.stock.indexOf(values.stock.toUpperCase() || '') == 0
      );
      this.setState({
        updateParam: !this.state.updateParam,
      });
    });
  };

  // 菜单栏- 重置按钮 事件
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { formValues } = this.state;
    form.resetFields();
    formValues.stock = '';
    dispatch({
      type: 'fund/GetBillRiskManage',
      payload: formValues,
      callback: () => {
        this.setState({
          listLoading: false,
        });
      },
    });
  };

  // 菜单栏- 展开 关闭 事件
  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  upload = () => {
    window.open('/upload/V/DataCenter/RYData.aspx');
  };

  search = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'fund/GetBillRiskManage',
      payload: formValues,
      callback: response => {},
    });
  };

  onSearch(value) {
    /*    const {
          rule: {filterData},
        } = this.props; */
    const { textboxValues, textLoading, suggestions } = this.state;
    this.state.textboxValues.key = value;
    const _this = this;
    // this.state.suggestions=[];
    if (value.length > 0) {
      this.props.dispatch({
        type: 'fund/GetTextBoxList',
        payload: textboxValues,
        callback: () => {
          const suggestionsData = [];
          for (let i = 0; i < _this.props.fund.filterData.list.length; i++) {
            suggestionsData.push(
              <Option key={_this.props.fund.filterData.list[i].address}>
                {_this.props.fund.filterData.list[i].value}
              </Option>
            );
          }
          _this.setState({
            suggestions: suggestionsData,
          });
        },
      });
    }
  }

  onSelect(value) {
    const { dispatch, form } = this.props;
    const { formValues, listLoading } = this.state;

    if (this.state.formValues.stock != undefined) {
      this.setState({
        listLoading: true,
      });
      dispatch({
        type: 'fund/GetBillRiskManage',
        payload: {
          stock: value,
        },
        callback: () => {
          this.setState({
            listLoading: false,
          });
        },
      });
    } else {
      message.warning('股票代码不能为空！');
    }
  }
}

export default BillGradeRiskControl;
